# coding: utf-8

import os
import time

from django.conf.urls import url
from django.http import JsonResponse

from project.settings import USER_TYPE
from apps.proxy.share import app_logger
from apps.proxy.handles import (loginout, proxy, product, school)

Error_Not_Login = JsonResponse({'retcode': 302, 'msg': '未登录', 'redirect':'/proxy/login/login.html'})
Error_Not_Proxy = JsonResponse({'retcode': 1, 'msg': '请以代理商帐号登录', 'redirect':'/proxy/login/login.html'})


mobile_Error_Not_Login = JsonResponse({'retcode': 99, 'msg': '未登录'})
mobile_Error_Not_Proxy = JsonResponse({'retcode': 100, 'msg': '请以代理商帐号登录'})


def CheckUserIsProxyForApiCaller(request, *args, **kwargs):
    execStartTime = time.time()
    if 'ut' not in request.session:
        return Error_Not_Login

    if request.session['ut'] != USER_TYPE.PROXY:
        return Error_Not_Proxy

    realCall = kwargs.pop('_viewFunc')
    ret = realCall(request, *args, **kwargs)

    execEndTime = time.time()
    # 所有大于100ms的操作，产生日志告警
    opTime = execEndTime-execStartTime
    if (opTime > 0.1):
        app_logger.warning('!! op takes %s seconds : function:%s %s  ' % (opTime,request.method,request.path))

    return ret

urlpatterns_api = []

def addPreCheck(urlpatterns,checkFunC):
    for pattern in urlpatterns:
        urlRegx = pattern[0]
        if type(urlRegx) != list:
            urlRegList = [urlRegx]
        else:
            urlRegList = urlRegx

        viewFunc = pattern[1]
        if len(pattern) == 2:
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, {'_viewFunc': viewFunc}))

        elif len(pattern) == 3:
            otherPara = pattern[2]
            otherPara['_viewFunc'] = viewFunc
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, otherPara))
        else:
            # print '!!unsupported url format : %s' % pattern
            os._exit(3)

urlpatterns_api_agrs = [
    ([r'^yj_proxy/$',
      r'^yj_proxy/(?P<resource_id>\w+)/$', ],
     proxy.handler.dispatch),


    ([r'^yj_products/$',
      r'^yj_products/(?P<resource_id>\w+)/$', ],
     product.handler.dispatch),

    ([r'^yj_schools/$',
      r'^yj_schools/(?P<resource_id>\w+)/$', ],
     school.handler.dispatch),

]

addPreCheck(urlpatterns_api_agrs, CheckUserIsProxyForApiCaller)


urlpatterns = [
    url(r'^login$', loginout.handler.login),
    url(r'^loginreq$', loginout.handler.loginReq),
    url(r'^logoutreq$', loginout.handler.logoutReq),
] + urlpatterns_api
